package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Test13BlockingQueue {

    public static void main(String[] args) {
        //arrayBlockingQueue();
        //synchronousQueue();
        producerConsumer();
    }

    private static void arrayBlockingQueue(){
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        try {
            BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
            System.out.println(blockingQueue.add("A"));
            System.out.println(blockingQueue.add("B"));
            System.out.println(blockingQueue.add("C"));
            //blockingQueue.add("");//java.lang.IllegalStateException: Queue full
            //System.out.println(blockingQueue.offer("D"));//失败返回false
            /*executorService.execute(()->{
                try {
                    blockingQueue.put("D");//当队列已满时阻塞 一直等待队列有位置才插入
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });*/
            executorService.execute(()->{
                try {
                    System.out.println(blockingQueue.offer("D", 2, TimeUnit.SECONDS));//超时取消
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });


            System.out.println(blockingQueue.remove());
            System.out.println(blockingQueue.remove());
            System.out.println(blockingQueue.remove());
            //blockingQueue.remove();//java.util.NoSuchElementException
            //System.out.println(blockingQueue.poll());//队列为空会返回空
            //System.out.println(blockingQueue.take());//当队列为空时一直阻塞 直到队列有位置才取
            executorService.execute(()->{
                try {
                    System.out.println(blockingQueue.poll(3, TimeUnit.SECONDS));//超时取消
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }


    private static void synchronousQueue(){
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        BlockingQueue blockingQueue = new SynchronousQueue();//只有一个容量的队列
        try {
            executorService.execute(()->{
                try {
                    System.out.println(Thread.currentThread().getName() + "-----" + "将AA插入队列……");
                    blockingQueue.put("AA");
                    System.out.println(Thread.currentThread().getName() + "-----" + "将BB插入队列……");
                    blockingQueue.put("BB");
                    System.out.println(Thread.currentThread().getName() + "-----" + "将CC插入队列……");
                    blockingQueue.put("CC");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            executorService.execute(()->{
                try {
                    TimeUnit.SECONDS.sleep(5);
                    blockingQueue.take();
                    System.out.println(Thread.currentThread().getName() + "-----获取到 AA");
                    TimeUnit.SECONDS.sleep(5);
                    blockingQueue.take();
                    System.out.println(Thread.currentThread().getName() + "-----获取到 BB");
                    TimeUnit.SECONDS.sleep(5);
                    blockingQueue.take();
                    System.out.println(Thread.currentThread().getName() + "-----获取到 CC");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }finally {
            executorService.shutdown();
        }
    }

    private static void producerConsumer(){
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
        MyResource myResource = new MyResource(blockingQueue);
        try {
            executorService.execute(()->{
                System.out.println("进入生产线程：" + Thread.currentThread().getName());
                myResource.produce();
            });

            executorService.execute(()->{
                System.out.println("进入消费线程：" + Thread.currentThread().getName());
                myResource.consumption();
            });

            TimeUnit.SECONDS.sleep(10);
            myResource.shutDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

class MyResource{

    private volatile boolean flag = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    private BlockingQueue<Integer> blockingQueue;

    public MyResource() {
    }

    public MyResource(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void produce(){
        int data;
        try {
            while (flag){
                data = atomicInteger.incrementAndGet();
                boolean offer = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
                if(offer){
                    System.out.println("生产成功 data: " + data);
                }else {
                    System.out.println("生产失败 data: " + data);
                }
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void consumption(){
        Integer data;
        try {
            while (flag){
                data = blockingQueue.poll(2,TimeUnit.SECONDS);
                if(data != null){
                    System.out.println("-----------消费成功 data: " + data);
                }else {
                    flag = false;
                    System.out.println("-----------消费失败,队列中已为空,退出");
                    return;
                }
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void shutDown(){
        this.flag = false;
    }
}
